package src.com.qf.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import src.com.qf.dao.GoodCarDao;
import src.com.qf.entity.GoodCar;
import src.com.qf.utils.JdbcUtil;

import java.sql.SQLException;
import java.util.List;

public class GoodCarDaoImpl implements GoodCarDao {
    private QueryRunner queryRunner = new QueryRunner();
    @Override
    public GoodCar selectGoodCarByUidAndGoodId(GoodCar car) {
        String sql = "select *from good_car where goodId=? and uid=?";
        GoodCar query = null;
        try {
            query = queryRunner.query(JdbcUtil.getCon(), sql, new BeanHandler<>(GoodCar.class), car.getGoodId(), car.getUid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    @Override
    public int insertGoodCar(GoodCar car) {
        String sql = "insert into good_car(goodId,goodNum,goodSum,uid) values(?,?,?,?)";
        int update = 0;
        try {
            update = queryRunner.update(JdbcUtil.getCon(), sql, car.getGoodId(), car.getGoodNum(), car.getGoodSum(), car.getUid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return update;
    }

    @Override
    public int updateGoodNumAndGoodSumById(GoodCar oldCar) {
        String sql = "update good_car set goodNum=? ,goodSum=? where id =?";
        int update = 0;
        try {
            update = queryRunner.update(JdbcUtil.getCon(), sql, oldCar.getGoodNum(), oldCar.getGoodSum(), oldCar.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return update;
    }

    @Override
    public List<GoodCar> selectGoodCarsByUid(Integer uid) {
        String sql = "select *from good_car where uid = ?";
        List<GoodCar> query = null;
        try {
            query = queryRunner.query(JdbcUtil.getCon(), sql, new BeanListHandler<>(GoodCar.class), uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    @Override
    public int deleteGoodCarById(Integer id) {
        String sql = "delete from good_car where id =?";
        int update = 0;
        try {
            update = queryRunner.update(JdbcUtil.getCon(), sql, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return update;
    }

    @Override
    public int deleteGoodCarByUid(Integer uid) {
        String sql = "delete from good_car where uid =?";
        int update = 0;
        try {

            update = queryRunner.update(JdbcUtil.getCon(), sql, uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return update;
    }
}
